package com.laoxu.java.collection;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 介绍Arrays类的使用
 *
 * @author laoxu
 * @create 2018-02-04
 **/
public class ArraysDemo {
    public static void main(String[] args) {
        //1. 填充数组fill
        fill();
        //2. 数组元素排序：sort
        sort();
        //3. 比较数组元素是否相等：equals
        equals();
        //4. 二分查找法找指定元素的索引值（下标）：binarySearch
        search();
        //5. 截取数组：copeOf和copeOfRange
        copy();
        //6. 将数组转换为List处理
        toList();

    }

    private static void print(int[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }

        System.out.println();
    }

    private static void fill() {
        int[] arr = new int[5];
        Arrays.fill(arr, 2);

        int[] arr1 = new int[5];
        Arrays.fill(arr1, 1, 3, 8);
        print(arr);
        print(arr1);
    }

    private static void sort(){
        int[] arr = {3,2,1,5,4};
        Arrays.sort(arr);
        int[] arr1 = {3,2,1,5,4};
        Arrays.sort(arr,1,3);
        print(arr);
        print(arr1);
    }

    private static void equals(){
        int[] arr1 = {1,2,3};
        int[] arr2 = {1,2,3};
        System.out.println("arr1=arr2?"+Arrays.equals(arr1,arr2));
    }

    private static void search(){
        int[] arr = {10,20,30,40,50};
        System.out.println(Arrays.binarySearch(arr, 20));
        System.out.println(Arrays.binarySearch(arr, 35));
        System.out.println(Arrays.binarySearch(arr, 0,3,30));
        System.out.println(Arrays.binarySearch(arr, 0,3,40));

    }

    private static void copy(){
        int[] arr = {10,20,30,40,50};
        int[] arr1 = Arrays.copyOf(arr, 3);
        int[] arr2 = Arrays.copyOfRange(arr,1,3);

        print(arr1);
        print(arr2);
    }

    private static void toList(){
        Integer[] arr = {10,20,30,40,50};
        List list = Arrays.asList(arr);
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.print(it.next()+" ");
        }
    }
}
